const ErrorModel = require('./ErrorModel')
const $request = require('../utils/request')
const request = require('request')

class RouteModel {

  constructor () {}

  action (ctx, next) {
    const action = ctx.methods === "POST" ?
    ctx.request.fields['action'] : ctx.query['action']
    if (this[action]) {
      const fn = this[action]
      return fn.call(this, ctx, next)
    } else {
      throw(ErrorModel(500, '无效的调用', ctx.query.traceId))
    }
  }

  async request (opts, traceId) {
    let result = null;
    Object.assign(opts, {headers: {
      "token": "f84b6bf8f17608f8a82a69b5abdf02cd",
      "userId": "1",
      "requestId": "8a82a69b5abdf02",
      "udid": "82a69b5abdf02cd"
    }})
    try {
      result = await $request(opts);
      if (result.status !== '0000') {
        throw(ErrorModel(result.status, result.message, traceId));
        result = null;
      }
    } catch (e) {
      let Error = null;
      if (e && e.__proto__.constructor.name == 'ErrorModel') {
        Error = e
      } else if (e.status && e.message) {
        Error = ErrorModel(e.status, e.message, traceId)
      } else {
        Error = ErrorModel(500, e, traceId)
      }
      throw(Error)
      result = null
    }
    return result
  }


}

module.exports = RouteModel
